﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using YDAT.YdatDB;

public partial class AddVolunteer : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            tbDateJoined.Text = System.DateTime.Now.ToShortDateString();
        }
    }
    protected void tbAge_TextChanged(object sender, EventArgs e)
    {

        if (Regex.IsMatch(tbAge.Text, @"^[0-9]+$"))
        {
            int age = Int32.Parse(tbAge.Text);

            if (age > 0 && age < 200)
            {
                DateTime dob = System.DateTime.Now.AddYears(age * -1);
                tbDOB.Text = String.Format("01/01/{0}", dob.Year);
                tbDOB.ForeColor = System.Drawing.Color.Red;
            }
        }
        else
        {
            tbAge.Text = "";
        }
    }
    protected void tbDOB_TextChanged(object sender, EventArgs e)
    {
        if (Regex.IsMatch(tbDOB.Text, @"^[0-1][0-9]/[0-3][0-9]/[1-2][90][0-9][0-9]$"))
        {
            DateTime dob = DateTime.Parse(tbDOB.Text);
            TimeSpan age = DateTime.Now.Subtract(dob);

            tbAge.Text = Math.Floor(age.TotalDays / 365).ToString();

            tbDOB.ForeColor = System.Drawing.Color.Empty;
        }
    }

    protected DateTime CalculateGraduationDate(int yearsToGraduate, int gradMonth)
    {
        if (System.DateTime.Now.Month < gradMonth) {
            yearsToGraduate--;
        }
        DateTime gradYear = System.DateTime.Now.AddYears(yearsToGraduate);

        DateTime gradDate = DateTime.Parse(String.Format("{0}/1/{1}",gradMonth,gradYear.Year));

        return gradDate;
    }


    protected bool UpdateVolunteer(int CurrentStepIndex)
    {
        YDATDataContext ydat = new YDATDataContext();

        if (CurrentStepIndex == 0 && hfVolunteerId.Value.Length == 0)
        {
            var volunteers = (from v in ydat.Volunteers
                                   //join ci in ydat.ContactInfos on v.contactInfoId equals ci.contactInfoId 
                                   //join vpx in ydat.VolunteerParentXrefs on v.volunteerId equals vpx.volunteerId
                                   //join p in ydat.Parents on vpx.parentId equals p.parentId into v2
                                   where v.firstName == tbFirstName.Text.Trim() 
                                    && v.lastName == tbLastName.Text.Trim()
                                   select v);
            //int cnt = volunteers.Count();
            //if (volunteers.Count() > 0)
            //{
            //    return true;
            //}
            foreach (var v in volunteers)
            {
                return true;
            }
            int c = volunteers.Count();
        }
        
        if (hfVolunteerId.Value.Length == 0)
        {
            //ContactInfo contactInfo = new ContactInfo();
            //ydat.ContactInfos.InsertOnSubmit(contactInfo);
            //ydat.SubmitChanges();

            //PhoneNumber phoneNumber = new PhoneNumber();
            //phoneNumber.contactInfoId = contactInfo.contactInfoId;
            //ydat.PhoneNumbers.InsertOnSubmit(phoneNumber);
            //ydat.SubmitChanges();

            

            
            ContactInfo parentContactInfo = new ContactInfo();
            parentContactInfo.address1 = tbFirstName.Text;
            parentContactInfo.PhoneNumbers.Add(new PhoneNumber());
            ydat.ContactInfos.InsertOnSubmit(parentContactInfo);
            Parent parent = new Parent();
            parent.ContactInfo = parentContactInfo;
            parent.firstName1 = tbFirstName.Text;
            parent.siteId = 1;
            ydat.Parents.InsertOnSubmit(parent);

            
            
            Volunteer volunteer = new Volunteer();
            volunteer.siteId = 1;
            volunteer.ContactInfo = new ContactInfo();


            if (ddlSchool.SelectedValue.Length > 0) volunteer.schoolId = Int32.Parse(ddlSchool.SelectedValue);
            volunteer.firstName = tbFirstName.Text;
            volunteer.lastName = tbLastName.Text;
            volunteer.gender = Char.Parse(ddlGender.SelectedValue);
            if (tbDOB.Text.Length > 0) volunteer.dob = DateTime.Parse(tbDOB.Text);
            volunteer.ethnicity = ddlEthnicity.SelectedValue;
            if (ddlGradeLevel.SelectedIndex > 0) {
                volunteer.graduationYear = CalculateGraduationDate(Int32.Parse(ddlGradeLevel.SelectedValue), Int32.Parse(ddlGradMonth.SelectedValue));
            }
            if (tbDateJoined.Text.Length > 0) volunteer.dateJoined = DateTime.Parse(tbDateJoined.Text);
            volunteer.allergies = tbAllergies.Text;
            volunteer.disabledFlg = bool.Parse(ddlDisabled.SelectedValue);
            volunteer.limitations = tbLimitations.Text;

            ydat.Volunteers.InsertOnSubmit(volunteer);


            volunteer.ContactInfo.address1 = tbFirstName.Text;
            volunteer.ContactInfo.PhoneNumbers.Add(new PhoneNumber());


            VolunteerParentXref volunteerParentXref = new VolunteerParentXref();
            volunteerParentXref.Parent = parent;
            volunteerParentXref.Volunteer = volunteer;
            volunteerParentXref.primaryFlg = true;
            ydat.VolunteerParentXrefs.InsertOnSubmit(volunteerParentXref);

            ydat.SubmitChanges();

            //hfVolunteerContactInfoId.Value = volunteer.contactInfoId.ToString();
            hfVolunteerId.Value = volunteer.volunteerId.ToString();
        }
        else
        {
            Volunteer volunteer = (from v in ydat.Volunteers
                                   where v.volunteerId == Int32.Parse(hfVolunteerId.Value)
                                   select v).First();
            if (ddlSchool.SelectedValue.Length > 0) volunteer.schoolId = Int32.Parse(ddlSchool.SelectedValue);
            volunteer.firstName = tbFirstName.Text;
            volunteer.lastName = tbLastName.Text;
            volunteer.gender = Char.Parse(ddlGender.SelectedValue);
            if (tbDOB.Text.Length > 0) volunteer.dob = DateTime.Parse(tbDOB.Text);
            volunteer.ethnicity = ddlEthnicity.SelectedValue;
            if (ddlGradeLevel.SelectedIndex > 0) {
                volunteer.graduationYear = CalculateGraduationDate(Int32.Parse(ddlGradeLevel.SelectedValue), Int32.Parse(ddlGradMonth.SelectedValue));
            }
            if (tbDateJoined.Text.Length > 0) volunteer.dateJoined = DateTime.Parse(tbDateJoined.Text);
            volunteer.allergies = tbAllergies.Text;
            volunteer.disabledFlg = bool.Parse(ddlDisabled.SelectedValue);
            volunteer.limitations = tbLimitations.Text;
            ydat.SubmitChanges();

        }

        return false;
    }

    protected void wzAddVolunteer_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = UpdateVolunteer(e.CurrentStepIndex);
    }
    protected void wzAddVolunteer_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = UpdateVolunteer(e.CurrentStepIndex);
    }
    protected void wzAddVolunteer_SideBarButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = UpdateVolunteer(e.CurrentStepIndex);
    }
    protected void wzAddVolunteer_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = UpdateVolunteer(e.CurrentStepIndex);
    }
    protected void wzAddVolunteer_CancelButtonClick(object sender, EventArgs e)
    {
        UpdateVolunteer(wzAddVolunteer.ActiveStepIndex);
    }


    protected void ldsPhoneNumbers_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        //YDATDataContext ydat = new YDATDataContext();
        //var phoneNumbers = (from p in ydat.PhoneNumbers 
        //                    where p.contactInfoId == Int32.Parse(hfVolunteerContactInfoId.Value)
        //                    select new { p.phoneNumberId, p.number, p.type, p.contactInfoId });
        //e.Result = phoneNumbers;
    }
}
